<!--
 * @Descripttion: 
 * @version: 
 * @Author: mmzhang
 * @Date: 2021-07-20 15:47:13
 * @LastEditTime: 2023-02-22 10:09:13
-->
<template>
  <div class="contractor-msg">
    <div class="flex flex-horizontal-between flex-vertical-center">
      <p class="title">{{ isSub ? '认购' : '签约' }}人信息</p>
      <Button type="primary" v-if="contractorShow" @click="addContractor">
        编辑{{ isSub ? '认购' : '签约' }}人
      </Button>
    </div>
    <div class="table-contractor">
      <Table :columns="columns" :data="data" border></Table>
    </div>
    <Modal v-model="contractorFlag" :title="`编辑${isSub ? '认购' : '签约'}人信息`" footer-hide>
      <div class="new-contractor">
        <div class="tab-tit">
          <span>序号</span>
          <span>
            <em style="color: #de1f37">*</em>
            {{ isSub ? '认购' : '签约' }}人姓名
          </span>
          <span>占比</span>
        </div>
        <div class="tab-con">
          <div class="tab-for" v-for="(item, index) in editData" :key="index">
            <span>{{ index + 1 }}</span>
            <span>
              <Select v-model="item.contractorId" placeholder="请选择">
                <Option
                  :value="Number(itemPerson.userId)"
                  :key="itemPerson.userId"
                  v-for="itemPerson in contractorIdList">
                  {{ itemPerson.value }}
                </Option>
              </Select>
            </span>
            <span>
              <Input v-model="item.divideInto" placeholder="请填写占比" type="number">
                <span slot="append">%</span>
              </Input>
            </span>
            <span class="delete hand" v-show="!item.principal" @click="deletePerson(index)">
              删除
            </span>
          </div>
        </div>
        <div class="tip-add hand" @click="addPerson">
          <Icon size="20" color="#2d8cf0" type="md-add-circle" />
          增加一个{{ isSub ? '认购' : '签约' }}人
        </div>
      </div>
      <div class="flex flex-horizontal-end">
        <Button @click="cancelFun" style="margin-right: 20px">取消</Button>
        <Button type="info" @click="submitFun">确认</Button>
      </div>
    </Modal>
  </div>
</template>
<script>
  import comMgr from '@/biz/sales/salesCommon'
  export default {
    props: ['detailMsg', 'orderStatusName', 'subscriptionId', 'buildingId', 'isSub'],
    data() {
      return {
        // 签约回款中  签约已全款  认购未签约
        contractorFlag: false,
        contractorShow: false,
        contractorIdList: [],
        editData: [],
        columns: [
          {
            title: '序号',
            type: 'index'
          },
          {
            title: (this.isSub ? '认购' : '签约') + '人姓名',
            key: 'principalName',
            render: (h, params) => {
              return h('span', params.row.principalName + '(' + params.row.workNo + ')')
            }
          },
          {
            title: '占比',
            key: 'divideInto',
            render: (h, params) => {
              return h('span', params.row.divideInto + '%')
            }
          }
        ],
        data: []
      }
    },
    created() {},
    mounted() {
      this.data = this.isSub ? this.detailMsg.divideSubscribers : this.detailMsg.divideContracts
      let statusName = this.detailMsg.orContractBaseInfoVO.statusName
      if (this.isSub) {
        this.contractorShow =
          this.orderStatusName == '认购'
            ? ['认购未签约', '认购已签约'].indexOf(statusName) > -1 && this.unlocking('0104010307')
            : false
      } else {
        this.contractorShow =
          this.orderStatusName == '签约'
            ? ['签约回款中', '签约已全款', '签约已交房'].indexOf(statusName) > -1 &&
              this.unlocking('0104030311')
            : false
      }

      // 获取签约人下拉
      if (this.contractorShow) {
        this.getContractor()
      }
    },
    methods: {
      // 签约人
      getContractor(query) {
        console.log(query, 'query')
        comMgr
          .getContractor(query, this.buildingId)
          .then((res) => {
            this.contractorIdList = res
            let ids = this.contractorIdList.map((item) => {
              return item.userId
            })
            this.data.forEach((item) => {
              if (ids.indexOf(item.contractorId) <= -1) {
                let obj = {
                  userId: item.contractorId,
                  userName: item.principalName,
                  workNo: item.workNo,
                  value: `${item.principalName}(${item.workNo}) ${
                    item.status == '1' ? '-在职' : '-离职'
                  }`
                }
                this.contractorIdList.push(obj)
              }
            })
          })
          .catch((err) => {
            this.contractorIdList = []
          })
      },
      addContractor() {
        this.editData = this.$tool.deepClone(this.data)
        this.contractorFlag = true
      },
      /**
       *
       */
      deletePerson(index) {
        this.editData.splice(index, 1)
      },
      /**
       * 添加签约人
       */
      addPerson() {
        this.editData.push({
          contractorId: '',
          divideInto: 0
        })
      },
      cancelFun() {
        this.contractorFlag = false
      },
      submitFun() {
        // 判断签约人 认购人姓名必填
        if (this.editData.some((item) => item.contractorId == '')) {
          this.$Message.error(`请检查，${this.isSub ? '认购' : '签约'}人姓名必填！`)
          return false
        }
        // 奖金占比
        let reg = /^([0-9]{1,2}|100)$/
        if (this.editData.some((item) => !reg.test(item.divideInto))) {
          this.$Message.error('请输入0-100内的数字')
          return false
        }
        // 判断奖金占比不能大于100%
        let total = this.editData.reduce((pre, cur) => {
          return Number(pre) + Number(cur.divideInto)
        }, 0)
        if (total > 100) {
          this.$Message.error('请检查，占比总计不能超过100%！')
          return false
        }

        // 判断签约人不可重复
        let personArr = this.editData.map((item) => item.contractorId)
        if (
          Array.from(new Set(personArr)).length != this.editData.length &&
          this.editData.length != 1
        ) {
          this.$Message.error(`请检查，${this.isSub ? '认购' : '签约'}人不可重复`)
          return false
        }
        //提交
        this.editData.forEach((item) => {
          item.type = 1
          item.subscriptionId = this.subscriptionId
          item.workNo = this.contractorIdList.filter(
            (itemPre) => itemPre.userId == item.contractorId
          )[0].workNo
          item.userName = this.contractorIdList.filter(
            (itemPre) => itemPre.userId == item.contractorId
          )[0].userName
          item.userId = item.contractorId
        })
        // '-'转换成null
        for (let i in this.editData) {
          this.$tool.transformationNullSet(this.editData[i])
        }
        let params = {
          contractDivides: this.editData,
          personType: this.isSub ? 'SUBSCRIBER' : 'CONTRACTOR',
          subscriptionId: this.subscriptionId
        }
        comMgr
          .addContractDivideFun(params)
          .then((res) => {
            this.contractorFlag = false
            this.$emit('onGetOrderDetail')
          })
          .catch((err) => {})
      }
    }
  }
</script>
<style lang="scss" scoped>
  .contractor-msg {
    margin-top: 40px;

    .table-contractor {
      margin-top: 20px;
    }
  }

  .new-contractor {
    .tab-tit {
      overflow: hidden;

      span {
        float: left;
        width: 40%;
        padding-left: 20px;
      }

      span:first-child {
        width: 10%;
        padding: 0;
      }
    }

    .tab-con {
      max-height: 400px;
      overflow: auto;

      .tab-for {
        overflow: hidden;
        margin-top: 5px;
        line-height: 32px;

        span {
          float: left;
          width: 40%;
          padding: 0 5px;
        }

        span:first-child {
          width: 10%;
        }

        .delete {
          width: 10%;
          float: right;
          text-align: center;
          color: #2d8cf0;
          cursor: pointer;
        }
      }
    }

    .tip-add {
      margin: 10px 0 10px 50px;
      color: #2d8cf0;
    }
  }
</style>
